using Microsoft.AspNetCore.Mvc;
using FServer.Core.Interfaces;
using FServer.Core.Entities;

namespace FServer.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class VersionController : ControllerBase
{
    private readonly IVersionService _versionService;
    private readonly ILogger<VersionController> _logger;

    public VersionController(IVersionService versionService, ILogger<VersionController> logger)
    {
        _versionService = versionService;
        _logger = logger;
    }

    /// <summary>
    /// 检查客户端版本
    /// </summary>
    /// <param name="request">版本检查请求</param>
    /// <returns>版本检查结果</returns>
    [HttpPost("check")]
    public async Task<IActionResult> CheckVersion([FromBody] VersionCheckRequest request)
    {
        try
        {
            _logger.LogInformation("客户端版本检查: {Version}, 平台: {Platform}", request.Version, request.Platform);

            var result = await _versionService.CheckVersionAsync(request.Version, request.Platform);

            var response = new
            {
                Success = true,
                NeedUpdate = result.NeedUpdate,
                ForceUpdate = result.ForceUpdate,
                LatestVersion = result.LatestVersion != null ? new
                {
                    result.LatestVersion.Version,
                    result.LatestVersion.VersionType,
                    result.LatestVersion.Description,
                    result.LatestVersion.UpdateContent,
                    result.LatestVersion.DownloadUrl,
                    result.LatestVersion.FileSize,
                    result.LatestVersion.FileMd5,
                    result.LatestVersion.ReleaseTime
                } : null,
                CurrentVersion = result.CurrentVersion != null ? new
                {
                    result.CurrentVersion.Version,
                    result.CurrentVersion.VersionType,
                    result.CurrentVersion.Description
                } : null,
                UpdateFiles = result.UpdateFiles.Select(f => new
                {
                    f.FileName,
                    f.FilePath,
                    f.FileSize,
                    f.FileMd5,
                    f.DownloadUrl,
                    f.FileType,
                    f.IsRequired,
                    f.Description
                }),
                UpdateDescription = result.UpdateDescription,
                ErrorMessage = result.ErrorMessage
            };

            return Ok(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "版本检查失败: {Version}", request.Version);
            return StatusCode(500, new { Success = false, Message = "版本检查失败" });
        }
    }

    /// <summary>
    /// 获取版本更新文件
    /// </summary>
    /// <param name="versionId">版本ID</param>
    /// <returns>更新文件列表</returns>
    [HttpGet("files/{versionId}")]
    public async Task<IActionResult> GetUpdateFiles(Guid versionId)
    {
        try
        {
            var files = await _versionService.GetUpdateFilesAsync(versionId);

            var response = files.Select(f => new
            {
                f.FileName,
                f.FilePath,
                f.FileSize,
                f.FileMd5,
                f.DownloadUrl,
                f.FileType,
                f.IsRequired,
                f.Description,
                f.IsCompressed,
                f.CompressedSize
            });

            return Ok(new { Success = true, Files = response });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取更新文件失败: {VersionId}", versionId);
            return StatusCode(500, new { Success = false, Message = "获取更新文件失败" });
        }
    }

    /// <summary>
    /// 获取版本信息
    /// </summary>
    /// <param name="versionId">版本ID</param>
    /// <returns>版本信息</returns>
    [HttpGet("{versionId}")]
    public async Task<IActionResult> GetVersion(Guid versionId)
    {
        try
        {
            var version = await _versionService.GetVersionAsync(versionId);
            if (version == null)
            {
                return NotFound(new { Success = false, Message = "版本不存在" });
            }

            var response = new
            {
                Success = true,
                Version = new
                {
                    version.Id,
                    version.Version,
                    version.MajorVersion,
                    version.MinorVersion,
                    version.PatchVersion,
                    version.VersionType,
                    version.IsForceUpdate,
                    version.MinSupportedVersion,
                    version.Description,
                    version.UpdateContent,
                    version.DownloadUrl,
                    version.FileSize,
                    version.FileMd5,
                    version.IsEnabled,
                    version.ReleaseTime
                }
            };

            return Ok(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取版本信息失败: {VersionId}", versionId);
            return StatusCode(500, new { Success = false, Message = "获取版本信息失败" });
        }
    }
}

/// <summary>
/// 版本检查请求
/// </summary>
public class VersionCheckRequest
{
    /// <summary>
    /// 客户端版本号
    /// </summary>
    public string Version { get; set; } = string.Empty;
    
    /// <summary>
    /// 平台 (Windows, Android, iOS)
    /// </summary>
    public string Platform { get; set; } = "Windows";
    
    /// <summary>
    /// 设备信息
    /// </summary>
    public string? DeviceInfo { get; set; }
    
    /// <summary>
    /// 客户端语言
    /// </summary>
    public string? Language { get; set; }
}
